package com.dingwen.treasure.web.interceptor;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.dingwen.treasure.base.constant.GlobalConstant;
import com.dingwen.treasure.base.context.UserVariableContextExt;
import com.dingwen.treasure.base.exception.AuthException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 　ServerProtectInterceptor: 微服务之间的拦截器 </br>
 *  TODO 优化点放行接口可配置
 * 　@author dingwen
 * 　@date 2022/6/24
 */
@Component
public class ServerProtectInterceptor implements HandlerInterceptor {
    /**
     * 之前
     *
     * @param request  要求
     * @param response 回答
     * @param handler  处理程序
     * @return boolean
     * @throws Exception 例外
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取token
        String token = request.getHeader(GlobalConstant.TREASURE_HEAD_TOKEN);

        // 获取用户id
        String userId = request.getHeader(GlobalConstant.TREASURE_HEAD_USER_ID);
        String headKnife4j = request.getHeader(GlobalConstant.TREASURE_HEAD_KNIFE4J);

        // 接口文档请求直接放行
        if (ObjectUtils.nullSafeEquals(headKnife4j,GlobalConstant.TREASURE_HEAD_KNIFE4J_VALUE)){
            return true;
        }

        if (StrUtil.isBlank(token) ||
                StrUtil.isBlank(userId)
                || !NumberUtil.isNumber(userId)
                || !token.equals(GlobalConstant.TREASURE_HEAD_TOKEN_VALUE)) {
            throw new AuthException(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.name());
        }

        // 网关处理
        // 设置请求上下文
        UserVariableContextExt.setUserId(Long.parseLong(userId));
        return true;
    }

    /**
     * 执行中
     *
     * @param request      要求
     * @param response     回答
     * @param handler      处理程序
     * @param modelAndView 模型和视图
     * @throws Exception 例外
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    /**
     * 响应之后进行删除
     *
     * @param request  要求
     * @param response 回答
     * @param handler  处理程序
     * @param ex       异常
     * @throws Exception 例外
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) {
        UserVariableContextExt.remove();
    }
}
